<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./js/jquery-3.6.0.js"></script>
    <script src="./js/jquery.validate.min.js"></script>
    <script src="./js/messages_zh.min.js"></script>
  </head>
  <body>
    <head>
      <style>
        .error {
          color: red;
        }
      </style>
    </head>
    <body>
      <div id="box">
        <form action="success.html" id="registerForm">
          <div>
            <label>用户名</label>
            <input type="text" name="username"/>
          </div>
          <div>
            <label>密码</label>
            <input type="password" name="pwd" id="password"/>
          </div>

          <div>
            <label>确认密码</label>
            <!--equalTo="#id值"-->
            <input type="password" name="rePwd"/>
          </div>

          <div>
            <label>年龄</label>
            <input type="number" name="age"/>
          </div>

          <div>
            <label>手机号码</label>
            <input type="text" name="phone" />
          </div>
          <div>
            <input type="submit" value="注册" />
          </div>
        </form>
      </div>
    </body>
</html>
<script>
  $(function () {
    $('#registerForm').validate({
      rules:{
        username:{
          required:true,
          minlength:8
        },
        pwd:{
          required:true
        },
        rePwd:{
          equalTo:"#password"
        },
        age:{
          min:0,
          max:150
        },
        phone:{
          required:true,
          phoneReg:true
        }
      },
      messages:{
        username:{
          required:"用户名不能为空~",
          minlength:"用户名至少8位~"
        },
        pwd:{
          required:"密码不能为空~"
        },
        rePwd:{
          equalTo:"两次密码输入不一致~"
        },
        age:{
          min:"年龄必须在0~150之间~",
          max:"年龄必须在0~150之间~"
        },
        phone:{
          required:"手机号码不能为空~",
          phoneReg:"手机号码格式不正确~"
        }
      }
    })

    //自定义正则验证规则
    $.validator.addMethod("phoneReg",function(value,element){
      var phoneReg = /^1[3|5|7|8|9]\d{9}$/
      return this.optional(element) || phoneReg.test(value)
    })
  })
</script>